//
//  TCPClient.swift
//  KCSwift
//
//  Created by apple on 2023/7/31.
//

import Foundation
import Network

@available(iOS 12.0, *)
class TCPClient {
    let host: NWEndpoint.Host
    let port: NWEndpoint.Port
    var connection: NWConnection?
    
    init(host: String, port: Int) {
        self.host = NWEndpoint.Host(host)
        self.port = NWEndpoint.Port(rawValue: UInt16(port))!
    }
    
    func connect() {
        let tcpOptions = NWProtocolTCP.Options()
        tcpOptions.enableKeepalive = true
        
        let parameters = NWParameters(tls: nil, tcp: tcpOptions)
        connection = NWConnection(host: host, port: port, using: parameters)
        
        connection?.stateUpdateHandler = { state in
            switch state {
            case .ready:
                print("Connected to server")
                self.send(message: "Hello, server!")
            case .failed(let error):
                print("Connection failed with error: \(error)")
            default:
                break
            }
        }
        
        connection?.start(queue: .main)
    }
    
    func send(message: String) {
        let data = message.data(using: .utf8)
        connection?.send(content: data, completion: .contentProcessed({ error in
            if let error = error {
                print("Failed to send message with error: \(error)")
            } else {
                print("Message sent successfully")
            }
        }))
    }
    
    func disconnect() {
        connection?.cancel()
    }
}


